<template>
  <div class="search">
    <n-card :bordered="false" class="mt-4 proCard">
      <n-grid cols="1" :x-gap="12">
        <n-gi>
          <n-form
            :model="queryForm"
            ref="queryFormRef"
            label-placement="left"
            inline>
            <n-grid :x-gap="12"  :cols="4" responsive="screen" @keydown.enter.native="handleSearch">
              <n-gi>
                <n-form-item label="岗位名称" path="jobName">
                  <n-input placeholder="请输入岗位名称" v-model:value="queryForm.jobName" />
                </n-form-item>
              </n-gi>
              <n-gi>
                <n-form-item style="margin-right: 0" class="br">
                  <n-space>
                    <n-button type="primary" @click="handleSearch">
                      <template #icon>
                        <n-icon>
                          <IosSearch/>
                        </n-icon>
                      </template>查询</n-button>
                    <n-button @click="handleReset">
                      重置</n-button>
                  </n-space>
                </n-form-item>
              </n-gi>
            </n-grid>
          </n-form>
          <n-grid :x-gap="12" :cols="2" class="operation" style="margin-bottom: 1vh" >
            <n-gi>
              <n-space>
                <n-button type="primary" @click="handleAdd">
                  <template #icon>
                    <n-icon>
                      <IosAdd/>
                    </n-icon>
                  </template>添加</n-button>
                <n-button type="error" @click="deleteAll">
                  <template #icon>
                    <n-icon>
                      <IosTrash/>
                    </n-icon>
                  </template>
                  删除</n-button>
              </n-space>
            </n-gi>
          </n-grid>
          <n-grid :cols="1" style="margin-bottom: 1vh;">
            <n-gi :span="1">
              <n-alert type="info" size="small">
                已选择
                <span class="select-count">{{selectedKeys.length}}</span> 项
                <a class="select-clear" @click="clearSelect" v-if="selectedKeys.length>0">清空</a>
              </n-alert>
            </n-gi>
          </n-grid>
          <n-grid :cols="1">
            <n-gi>
              <n-data-table
                ref="table"
                :columns="column"
                :pagination="pagination"
                :loading="loading"
                :data="data"
                :row-key="row => row.id"
                @update:checked-row-keys="handleCheck"
                @update:page-size="changePageSize"
                :checked-row-keys="selectedKeys"
              >
              </n-data-table>
            </n-gi>
          </n-grid>
        </n-gi>
      </n-grid>
      <n-modal v-model:show="quartzFormModal" :show-icon="false"  preset="dialog" :title="modalTitle" @update:show="closeForm">
        <n-form
          ref="quartzFormRef"
          label-placement="left"
          :model="quartzForm"
          :label-width="100"
          :rules="quartzFormRules"
        >
          <n-form-item path="jobClassName" label="任务类">
            <n-input
              v-model:value="quartzForm.jobClassName"
              placeholder="请输入任务类"
            >
            </n-input>
          </n-form-item>
          <n-form-item path="cronExpression" label="定时表达式">
            <n-input
              v-model:value="quartzForm.cronExpression"
              placeholder="请输入字典编码"
            >
            </n-input>
          </n-form-item>
          <n-form-item path="parameter" label="任务参数">
            <n-input
              v-model:value="quartzForm.parameter"
              placeholder="请输入任务参数"
            />
          </n-form-item>
          <n-form-item label="任务描述" path="description">
            <n-input v-model:value="quartzForm.description" type="textarea" placeholder="请输入任务描述" />
          </n-form-item>
        </n-form>
        <template #action>
          <n-space>
            <n-button @click="closeForm">取消</n-button>
            <n-button type="info" @loading="submitLoading" @click="submitForm">确定</n-button>
          </n-space>
        </template>
      </n-modal>
    </n-card>
  </div>
</template>

<script>
import {defineComponent,ref,h,onMounted,reactive} from 'vue'
import {useMessage,NButton,NTag,useDialog} from 'naive-ui'
import {IosSearch,IosAdd,IosTrash} from '@vicons/ionicons4'
import {deleteQuartz, quartzList, saveQuartz, updateQuartz,startJob,pauseJob} from "../../../api/system/quartz";

export default defineComponent({
  name: "Message",
  components:{
    NTag,
    IosTrash,
    IosAdd,
    IosSearch
  },
  setup(){
    const message=useMessage();
    const dialog=useDialog();
    let initQueryForm=()=>{
      return  {
        page:1,
        pageSize:10,
        type:null,
      }
    };
    const submitLoading=ref(false);
    const quartzFormModal=ref(false);
    let quartzForm=reactive({
      id:null,
      jobClassName:null,
      cronExpression:null,
      description:null,
      parameter:null
    });
    const quartzFormRef=ref(null);
    const data=ref([]);
    const queryForm=ref(initQueryForm());
    const selectedKeys=ref([]);
    const quartzFormRules=ref({
      jobClassName:{required:true,message:'请输入任务类',trigger:'blur'},
      cronExpression:{required:true,message:'请输入任务表达式',trigger:'blur'},
      description:{required:true,message:'请输入任务描述',trigger:'blur'}
    })
    const modalTitle=ref('');
    let pagination=reactive({
      itemCount:null,
      prefix ({ itemCount }) {
        return `共 ${itemCount} 项`
      },
      page: 1,
      pageSize: 10,
      showSizePicker: true,
      pageSizes: [10,20,30,40,50],
    });
    const loading=ref(false);
    const column=ref([
      {
        type: "selection",
        align: "center",
        fixed: "left"
      },
      {
        type: "index",
        align: "center",
        fixed: "left"
      },
      {
        title:'任务类',
        key:'jobClassName',
        align: 'center',
      },
      {
        title:'表达式',
        key:'cronExpression',
        align: 'center',
      },
      {
        title:'参数',
        key:'parameter',
        align: 'center',
      },
      {
        title:'任务描述',
        key:'description',
        align: 'center',
      },
      {
        title: '运行状态',
        align: 'center',
        key: 'type',
        render:function (row){
          if (row.status ==1) {
            return h("div", [
              h(NTag,
                {
                  type: 'success',
                },
                { default: () => '运行中' }
              )
            ]);
          } else if (row.status==0) {
            return h("div", [
              h(NTag,
                {
                  type: 'error',
                },
                { default: () => '已停止' }
              )
            ]);
          }
        }
      },
      {
        title: '操作',
        key: 'actions',
        align:'center',
        render: function (row) {
          let disableButton;
          if (row.status==0) {
            disableButton = h(
              NButton,
              {
                size: 'small',
                style: {
                  marginRight: "5px"
                },
                onClick: () => startTask(row)
              },
              {default: () => '恢复'}
            )
          } else if(row.status ==1) {
            disableButton=h(
              NButton,
              {
                size: "small",
                style: {
                  marginRight: "5px"
                },
                onClick: () => stopTask(row)
              },
              {default: () => '停止'}
            )
          }
          return h("div", [
            h(
              disableButton
            ),
            h(
              NButton,
              {
                type: "primary",
                size: "small",
                style: {
                  marginRight: "5px"
                },
                onClick: () => handleEdit(row)
              },
              {default: () => '编辑'}
            ),
            h(
              NButton,
              {
                type: "error",
                size: "small",
                onClick: () => handleDelete(row)
              },
              {default: () => '删除'}
            )
          ]);
        }
      }
    ]);
    const changePageSize=(value)=>{
      queryForm.value.pageSize=value;
      pagination.pageSize=value;
      loadQuartzData();
    };
    const stopTask=(record) =>{
      dialog.warning({
        title: '警告',
        content: '你确定暂定当前任务吗？',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick:()=>{
          pauseJob(record.id).then(res=>{
            if(res){
              message.success('操作成功');
              loadQuartzData();
            }
          })
        },
        onNegativeClick: () => {
        }
      })
    };
    const startTask=(record)=>{
      dialog.warning({
        title: '警告',
        content: '你确定暂定当前任务吗？',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick:()=>{
          startJob(record.id).then(res=>{
            if(res){
              message.success('操作成功');
              loadQuartzData();
            }
          })
        },
        onNegativeClick: () => {
        }
      })
    };

    const handleCheck = (keys) => {
      selectedKeys.value=keys;
    };
    const clearSelect = () => {
      selectedKeys.value=[];
    };
    const handleAdd = () => {
      quartzFormModal.value=true;
      modalTitle.value='添加定时任务';
    };
    const deleteAll = () => {
      if(selectedKeys.value.length<=0){
        message.warning('请选择您要删除的数据');
        return;
      }
      dialog.warning({
        title: '警告',
        content: '你确定要删除所选的'+selectedKeys.value.length+'条数据吗?删除后无法恢复',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick:()=>{
          const ids = selectedKeys.value.join(",");
          deleteQuartz({ids:ids}).then(res=>{
            if(res){
              message.success('删除成功');
              loadQuartzData();
            }
          })
        },
        onNegativeClick: () => {
        }
      })
    };
    const handleSearch = () => {
      loadQuartzData();
    };
    const handleReset = () => {
      Object.keys(queryForm.value).forEach((key)=>{
        queryForm.value[key]=initQueryForm()[key]||null;
      })
      loadQuartzData();
    };
    const handleEdit = (record) => {
      quartzFormModal.value=true;
      modalTitle.value='修改定时任务';
      quartzForm=Object.assign(quartzForm,record);
    };
    const handleDelete = (record) => {
      selectedKeys.value=[];
      selectedKeys.value.push(record.id);
      deleteAll();
    };
    const closeForm= () =>{
      quartzFormModal.value=false;
      Object.keys(quartzForm).forEach((key) => {
        quartzForm[key] = null;
      });
    };
    const submitForm =()=>{
      quartzFormRef.value.validate((errors)=>{
        if(!errors){
          submitLoading.value=true;
          let obj;
          if(quartzForm.id!=null){
            obj=updateQuartz(quartzForm)
          }else{
            obj=saveQuartz(quartzForm);
          }
          obj.then(res=>{
            if(res){
              message.success('操作成功');
              submitLoading.value=false;
              loadQuartzData();
              closeForm();
            }
          })
        }
      })
    };
    const loadQuartzData = () => {
      loading.value=true;
      quartzList(queryForm.value).then(res=>{
        data.value=res.records;
        pagination.itemCount=res.total;
        loading.value=false;
      })
    }
    onMounted(()=>{
      loadQuartzData();
    })
    return {
      queryForm,
      selectedKeys,
      pagination,
      column,
      loading,
      data,
      submitLoading,
      quartzForm,
      quartzFormRef,
      quartzFormModal,
      quartzFormRules,
      modalTitle,
      changePageSize,
      handleCheck,
      clearSelect,
      handleAdd,
      deleteAll,
      handleSearch,
      handleReset,
      handleEdit,
      handleDelete,
      submitForm,
      closeForm,
      stopTask,
      startTask
    }
  }
})
</script>

<style scoped>

</style>
